package com.leyou.auth.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.auth.entity.ClientInfo;
import com.leyou.auth.mapper.ClientMapper;
import com.leyou.auth.service.ClientService;
import com.leyou.common.exceptions.LyException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author 虎哥
 */
@Service
public class ClientServiceImpl extends ServiceImpl<ClientMapper, ClientInfo> implements ClientService {

    private final PasswordEncoder passwordEncoder;

    public ClientServiceImpl(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    @Value("${ly.jwt.key}")
    private String key;

    @Override
    public String getJwtKey(String clientId, String secret) {
        // 1.根据id查询ClientInfo
        ClientInfo clientInfo = query().eq("client_id", clientId).one();
        // 2.判断查询是否成功
        if (clientInfo == null) {
            // clientId是错误的，非法请求
            throw new LyException(400, "客户端验证失败，再捣乱就报警了！");
        }
        // 3.验证secret是否正确
        if (!passwordEncoder.matches(secret, clientInfo.getSecret())) {
            // secret是错误的
            throw new LyException(400, "客户端验证失败，再捣乱就报警了！");
        }
        // 4.如果正确，返回秘钥

        return key;
    }
}